<script setup lang="ts">
import {computed, nextTick, ref} from 'vue'
import {ElInput} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import GenerateProgress from "../../../../components/GenerateProgress.vue";
import {QuestionType} from "@/views/question/addQuestion/types/questionTypes.ts";

const props = defineProps<{
  difficulty?: number
  language?: string[]
  timeLimit?: number
  memoryLimit?: number
  tags?: string[]
  isEditorFullscreen?: boolean
  type?: number
}>()

const emit = defineEmits<{
  (e: 'update:tags', value: string[]): void
  (e: 'update:difficulty', value: number): void
  (e: 'update:language', value: string[]): void
  (e: 'update:timeLimit', value: number): void
  (e: 'update:memoryLimit', value: number): void
  (e: 'generate:tags'): void
}>()

const difficulties = [
  {label: '简单', value: 0},
  {label: '中等', value: 1},
  {label: '困难', value: 2}
]

const programmingLanguages = [
  {label: 'Java', value: 'java'},
  {label: 'Python', value: 'python'},
  {label: 'C++', value: 'cpp'},
  {label: 'JavaScript', value: 'javascript'}
]

// Tags 相关逻辑
const tagSuggestions = [
  '动态规划', '贪心算法', '深度优先搜索', '广度优先搜索',
  '二分查找', '回溯算法', '数组', '字符串', '链表', '树',
  '图论', '数学', '位运算', '排序', '模拟'
]

const filteredTags = computed(() => tagSuggestions)
const inputVisible = ref(false)
const inputValue = ref('')
const inputRef = ref<InstanceType<typeof ElInput> | null>(null)
const selectedTags = ref<string[]>([])

const handleInputConfirm = () => {
  if (inputValue.value.trim()) {
    const tagValue = inputValue.value.trim()
    if (props.tags && !props.tags.includes(tagValue)) {
      emit('update:tags', [...(props.tags || []), tagValue])
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}

const handleClose = (tag: string) => {
  if (props.tags) {
    const newTags = props.tags.filter(t => t !== tag)
    emit('update:tags', newTags)
    const selectedIndex = selectedTags.value.indexOf(tag)
    if (selectedIndex > -1) {
      selectedTags.value.splice(selectedIndex, 1)
    }
  }
}

const handleTagsSelect = (selectedTags: string[]) => {
  emit('update:tags', [...selectedTags])
}

const showInput = () => {
  inputVisible.value = true
  // 使用 nextTick 确保 input 元素已经渲染
  nextTick(() => {
    inputRef.value?.input?.focus()
  })
}

// 添加计算属性来处理双向绑定
const difficulty = computed({
  get: () => props.difficulty ?? 0,
  set: (value) => emit('update:difficulty', value)
})

const language = computed({
  get: () => props.language ?? [],
  set: (value) => emit('update:language', value)
})

const timeLimit = computed({
  get: () => props.timeLimit ?? 400,
  set: (value) => emit('update:timeLimit', value)
})

const memoryLimit = computed({
  get: () => props.memoryLimit ?? 65535,
  set: (value) => emit('update:memoryLimit', value)
})

const isGeneratingTags = ref(false)

// 生成标签处理函数
const handleGenerateTags = () => {
  isGeneratingTags.value = true
  emit('generate:tags')
}

// 提供重置方法给父组件
const resetGeneratingTags = () => {
  isGeneratingTags.value = false
}

defineExpose({
  resetGeneratingTags
})
</script>

<template>
  <div class="settings-section" :class="{ 'hide-when-fullscreen': isEditorFullscreen }">
    <div class="settings-grid">
      <!-- 左列 -->
      <div class="left-column">
        <!-- 上半部分：难度和语言 -->
        <div class="top-section">
          <el-form-item prop="difficulty">
            <template #label>
              难度<span class="required-asterisk">*</span>
            </template>
            <el-select
                v-model="difficulty"
                placeholder="请选择难度"
                class="full-width"
            >
              <el-option
                  v-for="item in difficulties"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item prop="language">
            <template #label>
              支持的编程语言<span class="required-asterisk">*</span>
            </template>
            <el-select
                v-model="language"
                multiple
                placeholder="请选择支持的编程语言"
                class="full-width"
                :disabled="type != QuestionType.PROGRAMMING"
            >
              <el-option
                  v-for="item in programmingLanguages"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 下半部分：运行限制 -->
        <div class="limits-container">
          <div class="limit-item">
            <div class="limit-header">
              <span class="limit-title">时间限制</span>
              <el-tag size="small" effect="plain" type="warning">TIME</el-tag>
            </div>
            <el-input-number
                v-model="timeLimit"
                :controls="false"
                class="limit-input"
                :disabled="type != QuestionType.PROGRAMMING"
            >
              <template #suffix>ms</template>
            </el-input-number>
          </div>

          <div class="limit-item">
            <div class="limit-header">
              <span class="limit-title">内存限制</span>
              <el-tag size="small" effect="plain" type="info">MEMORY</el-tag>
            </div>
            <el-input-number
                v-model="memoryLimit"
                :controls="false"
                class="limit-input"
                :disabled="type != QuestionType.PROGRAMMING"
            >
              <template #suffix>KB</template>
            </el-input-number>
          </div>
        </div>
      </div>

      <!-- 右列：标签 -->
      <el-form-item prop="tags" class="tags-section">
        <template #label>
          <div class="tag-label-container">
            <span>题目标签</span>
            <el-dropdown trigger="click" :teleported="true">
              <el-button class="button-new-tag" type="primary" plain size="small">
                <el-icon>
                  <Plus/>
                </el-icon>
                添加标签
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <div class="tags-selection-container">
                    <el-checkbox-group v-model="selectedTags" @change="handleTagsSelect">
                      <div
                          v-for="tag in filteredTags"
                          :key="tag"
                          class="tag-selection-item"
                      >
                        <el-checkbox :value="tag">{{ tag }}</el-checkbox>
                      </div>
                    </el-checkbox-group>
                  </div>
                  <el-dropdown-item divided @click="showInput">
                    <span class="custom-tag-option">
                      <el-icon><Plus/></el-icon>
                      自定义标签
                    </span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button color="#626aef" @click="handleGenerateTags">AI 生成</el-button>
          </div>
        </template>
        <div class="tags-container">
          <template v-if="tags?.length === 0 && !inputVisible">
            <div class="empty-tags">
              <span class="empty-text">暂无标签</span>
            </div>
          </template>
          <el-tag
              v-for="tag in tags"
              :key="tag"
              class="tag-item"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
              v-if="inputVisible"
              ref="inputRef"
              v-model="inputValue"
              class="tag-input"
              size="small"
              placeholder="请输入标签名称"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
          />
        </div>
        <GenerateProgress
            :visible="isGeneratingTags"
            title="AI正在生成标签"
            :fullscreen="false"
        />
      </el-form-item>
    </div>
  </div>
</template>

<style scoped>
.settings-section {
  background: var(--el-bg-color);
  border-radius: 8px;
  padding: 24px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.settings-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.left-column {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.top-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.full-width {
  width: 100%;
}

.limits-container {
  display: flex;
  gap: 32px;
  padding: 20px;
  background: var(--el-fill-color-blank);
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.12);
  justify-content: center;
  align-items: center;
}

.limit-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.limit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.limit-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.limit-input {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  padding-bottom: 12px;
  position: relative;
  display: inline-block;
}

:deep(.el-form-item__label)::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 6px;
  width: 24px;
  height: 2px;
  background-color: var(--el-color-primary);
  border-radius: 1px;
}

.limit-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  padding-bottom: 12px;
  position: relative;
  display: inline-block;
}

.limit-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 6px;
  width: 24px;
  height: 2px;
  background-color: var(--el-color-primary);
  border-radius: 1px;
}

.limit-input :deep(.el-input__wrapper) {
  padding-right: 8px;
  box-shadow: none;
  border: 1px solid var(--el-border-color);
}

.limit-input :deep(.el-input__wrapper:hover) {
  border-color: var(--el-border-color-hover);
}

.limit-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 1px var(--el-color-primary-light-8);
}

.limit-input :deep(.el-input__suffix) {
  color: var(--el-text-color-secondary);
}

@media screen and (max-width: 1200px) {
  .settings-grid {
    grid-template-columns: 1fr;
  }

  .top-section {
    grid-template-columns: 1fr 1fr;
    margin-bottom: 24px;
  }

  .limits-container {
    margin-bottom: 24px;
  }
}

@media screen and (max-width: 768px) {
  .settings-grid {
    grid-template-columns: 1fr;
  }

  .top-section {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .limits-container {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }

  .limit-item {
    min-width: 100%;
  }

  .tags-container {
    min-height: 100px;
  }
}

/* 添加标签相关样式 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: flex-start;
  padding: 12px;
  width: 100%;
  min-height: 120px;
  max-height: 200px;
  border-radius: 8px;
  background-color: var(--el-fill-color-blank);
  border: 1px solid rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  overflow-y: auto;
}

/* 自定义滚动条样式 */
.tags-container::-webkit-scrollbar {
  width: 6px;
}

.tags-container::-webkit-scrollbar-thumb {
  background-color: var(--el-border-color-lighter);
  border-radius: 3px;
}

.tags-container::-webkit-scrollbar-track {
  background-color: var(--el-fill-color-blank);
}

.tag-label-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.empty-tags {
  flex: 1;
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: center;
}

.empty-text {
  color: var(--el-text-color-placeholder);
  font-size: 14px;
}

.tag-item {
  height: 28px;
  padding: 0 10px;
  font-size: 13px;
  border-radius: 4px;
  margin: 2px;
}

.button-new-tag {
  height: 28px;
  padding: 0 12px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.tag-input {
  width: 120px;
  margin-right: 0;
}

.tags-selection-container {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px 0;
}

.tag-selection-item {
  padding: 8px 16px;
  transition: background-color 0.2s ease;
}

.tag-selection-item:hover {
  background-color: var(--el-fill-color-light);
}

.custom-tag-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

@media screen and (max-width: 768px) {
  .tags-container {
    min-height: 100px;
  }
}

.hide-when-fullscreen {
  display: none !important;
}

.required-asterisk {
  color: var(--el-color-danger);
  margin-left: 4px;
}
</style>
